package com.example.mybatispermission.config;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.naming.AuthenticationException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public DefaultWebSecurityManager securityManager(Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        Map<String, String> map = new HashMap<>();
        map.put("/login.html", "anon");
        map.put("/register.html", "anon");
        map.put("/user/login", "anon");
        map.put("/user/register", "anon");
        map.put("/unauth.html", "anon");
        map.put("/img/**", "anon");
        map.put("/js/**", "anon");
        map.put("/css/**", "anon");
        map.put("/**", "authc");
        bean.setFilterChainDefinitionMap(map);
        bean.setLoginUrl("/login.html");
        bean.setUnauthorizedUrl("/unauth.html");
        return bean;
    }
    @Bean
    public HandlerExceptionResolver resolver() {
        return (request, response, handler, ex) -> {
            if (ex instanceof AuthorizationException) {
                ModelAndView unauth = new ModelAndView("unauth");
                unauth.addObject("path", request.getServletPath());
                unauth.addObject("msg", ex.getMessage());
                return unauth;
            }
            return null;
        };
    }
}
